package cn.yogehaoren._return;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.TimeoutException;

/**
 * @author WangNing
 * @since 1.0
 */
public class ReturnProducer {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("k8s-node2");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();

        Channel channel = connection.createChannel();

        // 指定消息的确认模式
        channel.confirmSelect();

        String exchangeName = "test_return_exchange";
        String routingKey = "return_save";
        String routingERRKey = "no_save";

        // 添加监听器
        channel.addReturnListener(new ReturnListener() {
            /**
             *
             * @param replyCode 响应码
             * @param replyText 响应文本
             * @param exchange 消息指定的交换机
             * @param routingKey 消息指定的routingKEY
             * @param properties 消息的properties
             * @param body 消息的body
             * @throws IOException 可能抛出的异常
             */
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("----- handle ----return");
                System.out.println("replayCode: "+replyCode);
                System.out.println("replayText: "+replyText);
                System.out.println("exchange: "+ exchange);
                System.out.println("property: "+ Optional.of(properties).get());
                System.out.println("replayCode: "+new String(body));
            }
        });

        String msg = "Hello RabbitMQ send Return message!";
        // 第3个参数表示，如果路由不到broken是否自动删除该消息。只有设置为true ReturnListener才会生效
        channel.basicPublish(exchangeName, routingERRKey, true, null, msg.getBytes());

        // 关闭连接，线程会退出，否则不会主动退出
        // channel.close();
        // connection.close();

    }


}
